package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.ByteArrayOutputStream;

/**
 * 提供照片、二维码和字节数组（byte[]）之间的互相转换
 */
public class ImageUtils {

    /**
     * 将 drawable 转换为 Blob（字节数组）
     *
     * @param drawable Drawable 对象
     * @return Bitmap 对象
     */
    public static Bitmap drawable2bitmap(Drawable drawable) {
        Bitmap bitmap;
        // 如果是 BitmapDrawable，直接获取 Bitmap
        if (drawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) drawable).getBitmap();
        } else {
            // 如果是其他类型的 Drawable，手动创建 Bitmap
            int width = drawable.getIntrinsicWidth();
            int height = drawable.getIntrinsicHeight();
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
        }
        return bitmap;
    }


    /**
     * 将 Bitmap 转换为 Blob（字节数组）
     *
     * @param bitmap Bitmap 对象
     * @return byte[] Blob 数据
     */
    public static byte[] bitmap2Blob(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 将 Blob（字节数组）转换为 Bitmap
     *
     * @param blob byte[] 数据
     * @return Bitmap 对象
     */
    public static Bitmap blob2Bitmap(byte[] blob) {
        return BitmapFactory.decodeByteArray(blob, 0, blob.length);
    }
}
